# encoding=utf-8
"""
响应对象业务校验
"""
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request


class BizValidator(BaseValidateMiddleware):

    def validate_supplier(self, request, response, spider):
        # 已触发反爬
        if '过度刷新行为' in response.text:
            meta = request.meta
            cur_page = meta.get('page')
            spider.logger.info('反爬重试[supplier]<p=%s>' % cur_page)
            return retry_request(request)

        return response

    def validate_sku(self, request, response, spider):
        # 已触发反爬
        if '过度刷新行为' in response.text:
            meta = request.meta
            cur_page = meta.get('page')
            sp_id = meta.get('supplierId')
            cat_id = meta.get('catalogId')
            spider.logger.info('反爬重试[sku]<cat=%s, sp=%s, p=%s>' % (cat_id, sp_id, cur_page))
            return retry_request(request)

        return response

    def validate_item(self, request, response, spider):
        # 已触发反爬
        if not response.text or '过度刷新行为' in response.text:
            meta = request.meta
            page = meta.get('page')
            cat_id = meta.get('catalogId')
            sp_id = meta.get('supplierId')

            spider.logger.info('反爬重试[item]：<cat=%s, sp=%s, p=%s>' % (cat_id, sp_id, page))
            return retry_request(request)

        return response

    def validate_group(self, request, response, spider):
        # 已触发反爬
        if '过度刷新行为' in response.text:
            sku_id = request.meta.get('skuId')
            spider.logger.info('反爬重试[group]：%s' % sku_id)
            return retry_request(request, -100)

        return response

    def validate_order(self, request, response, spider):
        # 已触发反爬
        if '过度刷新行为' in response.text:
            sku_id = request.meta.get('skuId')
            spider.logger.info('反爬重试[order]：%s' % sku_id)

            return retry_request(request, -100)

        return response
